/*******************************************************************************
 * Copyright (c) 2011 - 2012 TXT e-solutions SpA
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 *
 * Authors:
 *     Cristoforo Seccia (TXT e-solutions SpA)
 *     Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *      Domenico Rotondi (TXT e-solutions SpA)
 *******************************************************************************/
package it.txt.access.capability.revocation.wizard.panel;

import it.txt.access.capability.commons.filter.FilterJKS;
import it.txt.access.capability.revocation.wizard.panel.controller.ControllerPanelKeystore;

import java.awt.Frame;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Cristoforo Seccia (TXT e-solutions SpA)
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT network.txtgroup.com)
 */
public class PanelKeystore extends javax.swing.JPanel {

    private static final long serialVersionUID = 1031014816001692569L;
    private File currentKeystoreDirecotory = null;
    private ControllerPanelKeystore controller;
    private boolean isCertificatePswOk = false;
    private boolean isKeystorePathOk = false;
    private boolean isKeystorePswOPk = false;
    private FilterJKS filterKeystore;
    private JFileChooser keystoreChooser;
    private final String title;

    /** Creates new form PanelWelcome */
    public PanelKeystore(String title, Frame container, ControllerPanelKeystore cpw) {
        this.title = title;
        initComponents();
        checkKeystorePathDocument();
        checkKeystorePasswordDocument();
        checkCertificatePasswordDocument();
        controller = cpw;
        filterKeystore = new FilterJKS();
        keystoreChooser = new JFileChooser();
        keystoreChooser.setFileFilter(filterKeystore);
        keystoreChooser.setMultiSelectionEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        centerPanel = new javax.swing.JPanel();
        centerTitlePanel = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        welcomeLabel = new javax.swing.JLabel();
        keystorePathLabel = new javax.swing.JLabel();
        keystorePswLabel = new javax.swing.JLabel();
        keystorePswText = new javax.swing.JPasswordField();
        keystorePathText = new javax.swing.JTextField();
        keystorePathButton = new javax.swing.JButton();
        keystoreNoteslabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        keystoreNotesArea = new javax.swing.JTextArea();
        certificatePswLabel = new javax.swing.JLabel();
        certificatePswText = new javax.swing.JPasswordField();
        policyGetCertificateButton = new javax.swing.JButton();
        label_required_field_legenda = new javax.swing.JLabel();

        centerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        centerTitlePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(this.title));

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("bundles/PanelKeystore"); // NOI18N
        welcomeLabel.setText(bundle.getString("subtitle")); // NOI18N

        keystorePathLabel.setText(bundle.getString("keystorePathLabel")); // NOI18N

        keystorePswLabel.setText(bundle.getString("keystorePasswordLabel")); // NOI18N

        keystorePswText.setToolTipText("");
        keystorePswText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));
        keystorePswText.setMinimumSize(new java.awt.Dimension(2, 20));
        keystorePswText.setPreferredSize(new java.awt.Dimension(2, 20));

        keystorePathText.setEditable(false);
        keystorePathText.setToolTipText(bundle.getString("keystorePath")); // NOI18N
        keystorePathText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));
        keystorePathText.setMinimumSize(new java.awt.Dimension(2, 20));
        keystorePathText.setPreferredSize(new java.awt.Dimension(2, 20));

        keystorePathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons_16x16/Open_16x16.png"))); // NOI18N
        keystorePathButton.setText(bundle.getString("loadButton")); // NOI18N
        keystorePathButton.setToolTipText("Opens a file chooser to select the Java keystore holding the certificate to sign the revocation");
        keystorePathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                keystorePathButtonActionPerformed(evt);
            }
        });

        keystoreNoteslabel.setText(bundle.getString("certificateAcquisitionResultLabel")); // NOI18N

        keystoreNotesArea.setColumns(20);
        keystoreNotesArea.setEditable(false);
        keystoreNotesArea.setFont(new java.awt.Font("Monospaced", 1, 14)); // NOI18N
        keystoreNotesArea.setRows(5);
        jScrollPane1.setViewportView(keystoreNotesArea);

        certificatePswLabel.setText(bundle.getString("certificatePasswordLabel")); // NOI18N

        certificatePswText.setToolTipText("");
        certificatePswText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));
        certificatePswText.setMinimumSize(new java.awt.Dimension(2, 20));
        certificatePswText.setPreferredSize(new java.awt.Dimension(2, 20));

        policyGetCertificateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons_24x24/Certificate_24x24.gif"))); // NOI18N
        policyGetCertificateButton.setText(bundle.getString("getCertificateButton")); // NOI18N
        policyGetCertificateButton.setEnabled(false);
        policyGetCertificateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                policyGetCertificateButtonActionPerformed(evt);
            }
        });

        label_required_field_legenda.setText(bundle.getString("requiredFieldLegendaLabel")); // NOI18N

        javax.swing.GroupLayout centerTitlePanelLayout = new javax.swing.GroupLayout(centerTitlePanel);
        centerTitlePanel.setLayout(centerTitlePanelLayout);
        centerTitlePanelLayout.setHorizontalGroup(
            centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerTitlePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(welcomeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator1)
                    .addGroup(centerTitlePanelLayout.createSequentialGroup()
                        .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(certificatePswLabel)
                            .addComponent(keystorePswLabel)
                            .addComponent(keystorePathLabel))
                        .addGap(18, 18, 18)
                        .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, centerTitlePanelLayout.createSequentialGroup()
                                .addComponent(keystorePathText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(keystorePathButton))
                            .addComponent(keystorePswText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(certificatePswText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(centerTitlePanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(policyGetCertificateButton))
                    .addComponent(jScrollPane1)
                    .addGroup(centerTitlePanelLayout.createSequentialGroup()
                        .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(keystoreNoteslabel)
                            .addComponent(label_required_field_legenda))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        centerTitlePanelLayout.setVerticalGroup(
            centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerTitlePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(welcomeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keystorePathLabel)
                    .addComponent(keystorePathText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(keystorePathButton))
                .addGap(18, 18, 18)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keystorePswLabel)
                    .addComponent(keystorePswText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(certificatePswLabel)
                    .addComponent(certificatePswText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(policyGetCertificateButton)
                .addGap(26, 26, 26)
                .addComponent(keystoreNoteslabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(label_required_field_legenda)
                .addContainerGap())
        );

        javax.swing.GroupLayout centerPanelLayout = new javax.swing.GroupLayout(centerPanel);
        centerPanel.setLayout(centerPanelLayout);
        centerPanelLayout.setHorizontalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(centerTitlePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        centerPanelLayout.setVerticalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(centerTitlePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(centerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(centerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void keystorePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keystorePathButtonActionPerformed
        handleKeystorePathButtonActionPerformed();
    }//GEN-LAST:event_keystorePathButtonActionPerformed

    private void policyGetCertificateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_policyGetCertificateButtonActionPerformed
        handleGetCertificateButtonActionPerformed();
    }//GEN-LAST:event_policyGetCertificateButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel centerPanel;
    private javax.swing.JPanel centerTitlePanel;
    private javax.swing.JLabel certificatePswLabel;
    private javax.swing.JPasswordField certificatePswText;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea keystoreNotesArea;
    private javax.swing.JLabel keystoreNoteslabel;
    private javax.swing.JButton keystorePathButton;
    private javax.swing.JLabel keystorePathLabel;
    private javax.swing.JTextField keystorePathText;
    private javax.swing.JLabel keystorePswLabel;
    private javax.swing.JPasswordField keystorePswText;
    private javax.swing.JLabel label_required_field_legenda;
    private javax.swing.JButton policyGetCertificateButton;
    private javax.swing.JLabel welcomeLabel;
    // End of variables declaration//GEN-END:variables


    private void handleKeystorePathButtonActionPerformed(){
        if (currentKeystoreDirecotory == null) {
            keystoreChooser.setCurrentDirectory(new File("."));
        }
        else {
            keystoreChooser.setCurrentDirectory(currentKeystoreDirecotory);
        }
        int returnValue = keystoreChooser.showOpenDialog(getRootPane());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File keystoreFile = keystoreChooser.getSelectedFile();
            currentKeystoreDirecotory = keystoreChooser.getSelectedFile().getParentFile();
            keystorePathText.setText(keystoreFile.getAbsolutePath());
            keystorePathText.setBorder(javax.swing.BorderFactory.createLineBorder(
                    new java.awt.Color(0, 0, 0)));
        }
        validatePanelStatus();
    }

    private void handleGetCertificateButtonActionPerformed(){
        if (controller.recoverAccessRightsCapabilityX509Certificate(currentKeystoreDirecotory,
                keystorePswText.getPassword(), certificatePswText.getPassword())) {
            keystoreNotesArea.setText(controller.getX509CertificatePublicValuesToString());
            keystoreNotesArea.setCaretPosition(0);
        }
        validatePanelStatus();
    }

    private void checkKeystorePathDocument() {

        keystorePathText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                String strKeystorePath = keystorePathText.getText();
                try {
                    File typedFile = new File(strKeystorePath);
                    if (!strKeystorePath.equals("")
                            && filterKeystore.accept(typedFile)) {

                        keystorePathText.setBorder(
                                javax.swing.BorderFactory.createLineBorder(
                                new java.awt.Color(0, 0, 0)));

                        currentKeystoreDirecotory = typedFile;

                        isKeystorePathOk = true;

                    } else {

                        keystorePathText.setBorder(
                                javax.swing.BorderFactory.createLineBorder(
                                new java.awt.Color(255, 0, 0)));

                        isKeystorePathOk = false;
                    }
                } catch (Exception ex) {
                    isKeystorePathOk = false;
                }

                policyGetCertificateButton.setEnabled(isKeystorePathOk
                        && isKeystorePswOPk && isCertificatePswOk);
            }
        });
    }

    private void checkKeystorePasswordDocument() {

        keystorePswText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                char[] strKeystorePsw = keystorePswText.getPassword();
                if (strKeystorePsw.length > 0) {
                    keystorePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(0, 0, 0)));
                    isKeystorePswOPk = true;
                } else {
                    keystorePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(255, 0, 0)));
                    isKeystorePswOPk = false;
                }
                policyGetCertificateButton.setEnabled(isKeystorePswOPk
                        && isKeystorePathOk && isCertificatePswOk);
            }
        });
    }

    private void checkCertificatePasswordDocument() {

        certificatePswText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                char[] strCertificatePsw = certificatePswText.getPassword();
                if (strCertificatePsw.length > 0) {
                    certificatePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(0, 0, 0)));
                    isCertificatePswOk = true;
                } else {
                    certificatePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(255, 0, 0)));
                    isCertificatePswOk = false;
                }
                policyGetCertificateButton.setEnabled(isCertificatePswOk
                        && isKeystorePathOk && isKeystorePswOPk);
            }
        });
    }

    public void validatePanelStatus() {
        boolean b = isKeystorePathOk && isKeystorePswOPk && isCertificatePswOk;
        policyGetCertificateButton.setEnabled(b);
    }
}
